//
//  loginViewController.swift
//  微妙
//
//  Created by DW on 16/9/20.
//  Copyright © 2016年 DW. All rights reserved.
//

import UIKit
import TextFieldEffects
import QorumLogs
import Alamofire
import SlideMenuControllerSwift

class loginViewController: UIViewController ,UITextFieldDelegate,PopMenuDelegate,UIViewControllerTransitioningDelegate,RCAnimatedImagesViewDelegate{
    
    @IBOutlet weak var userNameInsertLable: HoshiTextField!
    @IBOutlet var userPassInsertLable: HoshiTextField!
    
    @IBAction func forgetBtnAction(sender: AnyObject) {
        let single_forgectViewMode = NSBundle.mainBundle().loadNibNamed("forgetPassPopView", owner: nil, options: nil).first as! forgetPassPopView
        createPopView(single_forgectViewMode)
        menuView.showMenuView()
    }
    
    
    @IBOutlet var userHeaderImage: UIImageView!
    
    
    static var userCardID:String?
    
    var user_tel:String = ""
    var user_pas:String = ""
    var menuView: PopMenu!
    var loginMark:Bool = true
    
    var registerFlag = 0 //0:为qq微信注册跳转，2为普通用户注册
    var backImage:RCAnimatedImagesView?
    
    var loginBtn: UIButton?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //添加背景图像
        self.backImage = RCAnimatedImagesView(frame: CGRect(x: 0, y: 0, width: commonVariable.SYSTEM_WIDTH, height: commonVariable.SYSTEM_HEIGHT))
        self.view.addSubview(self.backImage!)
        self.backImage?.delegate = self
        //设置数字键盘
        userNameInsertLable.inputView = commonVariable.NUMPAD
        userNameInsertLable.delegate = self
        userPassInsertLable.delegate = self
        //添加点击空白收回键盘
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTapBlank:"))
        //头像设置
        userHeaderImage.layer.masksToBounds = true
        userHeaderImage.layer.cornerRadius = 80 / 2
        userHeaderImage.userInteractionEnabled = true
        userHeaderImage.contentMode = UIViewContentMode.ScaleAspectFill
        userHeaderImage.alpha = 0.8
        
        loginBtn = commonTool.initLoginBtn("登 录", rect: CGRect(x: 0, y: 0, width: 100, height: 30), center: CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 400))
        loginBtn?.addTarget(self, action: "loginAction", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(loginBtn!)
        
    }
    //登录的行为
    func loginAction(){
        if(userNameInsertLable.text! == "" || userPassInsertLable.text! == ""){
            SweetAlert().showAlert("亲~", subTitle: "请填写完成自己的手机号码与密码！", style: AlertStyle.Warning)
            return
        }
        self.view.userInteractionEnabled = false
        commonVariable.LOADING_PACMAN.center = commonVariable.WINDOWSCENTER
        self.view.addSubview(commonVariable.LOADING_PACMAN)
        commonVariable.LOADING_PACMAN.startAnimation()
        
        let body = ["userTel":"\(userNameInsertLable.text!)","userPass":"\(userPassInsertLable.text!)"]
        QL1(body)
        Alamofire.request(.POST, commonVariable.USERLOGIN,parameters:body,headers:nil).responseJSON() {
            response in
            self.view.userInteractionEnabled = true
            commonVariable.LOADING_PACMAN.stopAnimation()
            commonVariable.LOADING_PACMAN.removeFromSuperview()
            guard let JSONDIC = response.result.value else {
                QL4(response.result.error)
                switch response.result.error!.code {
                case -1009 :
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                case 3840:
                    SweetAlert().showAlert("对不起", subTitle: "服务出现故障，请联系管理员", style: AlertStyle.Error)
                case -1001 :
                    SweetAlert().showAlert("对不起", subTitle: "上传信息超时", style: AlertStyle.Error)
                default:
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                }
                return }
            QL2(JSONDIC)
            let resultDict = JSONDIC as? NSDictionary
            let jsonObj = JSON(JSONDIC)
            let errorCode = jsonObj["errorcode"].intValue
            let errorMsg = jsonObj["message"].stringValue
            
            QL2(errorMsg)
            if errorCode != 1 {
                SweetAlert().showAlert("对不起", subTitle: "\(errorMsg)", style: AlertStyle.Warning)
            }else{
                //写入文件,利用语法糖解决dic问题
                let tempdataDic = jsonObj["userInfo"]
                let dataDic:NSMutableDictionary = NSMutableDictionary()
                for item in tempdataDic {
                    dataDic[item.0] = item.1.stringValue
                }
                QL2(dataDic)
                commonVariable.LOCAL_USER = User.parse(dict: dataDic)
                //普通账户信息
                let commonAccountInfoDic = jsonObj["commonAccountInfo"]
                let cadataDic:NSMutableDictionary = NSMutableDictionary()
                for item in commonAccountInfoDic {
                    cadataDic[item.0] = item.1.stringValue
                }
                QL2(dataDic)
                commonVariable.COMMONACCOUNT = commonAccount.parse(dict: cadataDic)
                
                //利用reflect存档
                let accountResult = User.save(obj: commonVariable.COMMONACCOUNT, name: commonVariable.ACCOUNTPATH, duration: NSTimeInterval(0))
                cadataDic.writeToFile(commonVariable.ACCOUNTPATH, atomically: true)
                
                //利用reflect存档
                let result = User.save(obj: commonVariable.LOCAL_USER, name: commonVariable.USERINFOPATH, duration: NSTimeInterval(0))
                dataDic.writeToFile(commonVariable.USERINFOPATH, atomically: true)
                //进入主页
                commonVariable.accountArr = []
                
                commonVariable.USERLIST = userListController()
                commonVariable.RECORDERCONTROLLER = recordController()
                
                let slideMenuController = SlideMenuController(mainViewController: commonVariable.RECORDERCONTROLLER!, leftMenuViewController: commonVariable.USERLIST!)
                commonVariable.HOSTCLASS = slideMenuController
                self.presentViewController(commonVariable.HOSTCLASS!, animated: true) { () -> Void in
                    
                }
            }
        }
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.view.userInteractionEnabled = true
        if(commonVariable.LOCAL_USER != nil){
            userNameInsertLable.text = commonVariable.LOCAL_USER?.userTel
            if(commonVariable.LOCAL_USER?.userPass?.characters.count <= 16){
                userPassInsertLable.text = commonVariable.LOCAL_USER?.userPass
            }else{
                userPassInsertLable.text = ""
            }
        }
        //背景动画动起来
        self.backImage?.startAnimating()
    }
    override func viewDidDisappear(animated: Bool) {
        super.viewDidAppear(animated)
        self.backImage?.stopAnimating()
    }
    //MARK:backimge的代理
    func animatedImagesNumberOfImages(animatedImagesView: RCAnimatedImagesView!) -> UInt {
        return 2
    }
    func animatedImagesView(animatedImagesView: RCAnimatedImagesView!, imageAtIndex index: UInt) -> UIImage! {
        return UIImage(named: "login_background")
    }

    //MARK: -textfield代理实现
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    //对输入进行检测
    func textFieldDidEndEditing(textField: UITextField) {
        //对用户名和密码进行限制
        if textField == self.userNameInsertLable  && textField.text != ""{
            var length = self.userNameInsertLable.text!.characters.count
            if length != 11 {
                SweetAlert().showAlert("请输入您的11位手机号码")
                self.userNameInsertLable.text = ""
                textField.resignFirstResponder()
            }
        }else if textField == self.userPassInsertLable  && textField.text != ""{
            textField.resignFirstResponder()
        }
    }
    func handleTapBlank(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
            self.userNameInsertLable.resignFirstResponder()
            self.userPassInsertLable.resignFirstResponder()
        }
        sender.cancelsTouchesInView = false
    }
    //创建popView
    func createPopView(popView:forgetPassPopView){
        menuView = PopMenu(frame: self.view.frame,isDetail: true,detailPage: popView)
        menuView.isShowDetail = true
        menuView.delegate = self
        self.view.addSubview(menuView!)
    }
    //PopView的代理方法
    func didClickMenu(index: Int) {
    }
    func backToPage(popView: UIView) {
        let tempView = popView as! forgetPassPopView
        tempView.confirmLabel.resignFirstResponder()
        tempView.inputTelNo.resignFirstResponder()
        tempView.passLable.resignFirstResponder()
    }
    
    //跳转注册界面传参
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "registerPage"{
            let tempVC = segue.destinationViewController as! UINavigationController

        }
    }
    
    
    func getInsertResult(result: Bool) {
        
    }

    /**
     对reg页面的传参进行处理
     
     - parameter segue: reg页面
     */
    @IBAction func unwindToList(segue : UIStoryboardSegue)
    {
        self.registerFlag = 0
    }
    
    @IBAction func unwindToLogin(segue : UIStoryboardSegue)
    {
        QL2("我回来啦")
        self.registerFlag = 0
    }
}